package handlers

import (
	"go-ddd-ecommerce/internal/application/dto"
	"go-ddd-ecommerce/internal/application/services"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

type OrderController struct {
	orderService *services.OrderAppService
}

func NewOrderController(orderService *services.OrderAppService) *OrderController {
	return &OrderController{orderService: orderService}
}

type PurchaseRequest struct {
	UserID    string `json:"user_id"`
	ProductID string `json:"product_id" binding:"required"`
	Quantity  int    `json:"quantity" binding:"required,min=1"`
}

type GetUserOrdersRequest struct {
	UserID string `json:"user_id"`
}

// 购买商品
func (oc *OrderController) Purchase(c *gin.Context) {

	var req PurchaseRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	cmd := dto.CreateOrderDTO{
		UserID:    uuid.MustParse(req.UserID),
		ProductID: uuid.MustParse(req.ProductID),
		Quantity:  req.Quantity,
	}
	order, err := oc.orderService.Purchase(cmd)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{
		"message": "购买成功完成",
		"order":   order,
	})
}

// 获取用户订单
func (oc *OrderController) GetUserOrders(c *gin.Context) {
	var req GetUserOrdersRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	cmd := dto.GetOrderByUserIDDTO{
		UserID: uuid.MustParse(req.UserID),
	}

	orders, err := oc.orderService.GetUserOrders(cmd)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, orders)
}
